<?php

namespace App\Models;

use App\Util\Tool;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class AutoFollowPlan extends Model
{
    protected $table = "c_auto_follow_plans";

    public function clinic()
    {
        return $this->hasOne('App\Models\ClinicCategory', 'id', 'clinic_id');
    }
    public function planmessage()
    {
        return $this->hasMany('App\Models\PlanMessage');
    }

    /**
     * @param $filter
     * @return array|string
     * 添加自动随访
     */
    public function add($filter)
    {
        try {
            DB::beginTransaction(); // 开始事务
            $FollowPlanTemplateLib = new FollowPlanTemplateLib();
            //处理数据,整合消息和时间
            $mes = $this->handelCombinationData($filter);
//            if (isset($filter['auto_id']) && !empty($filter['auto_id'])) {
//                $result = $this->addPlanMessage($filter); //添加计划消息
//                if(isset($filter['temp_id'])){
//                    $FollowPlanTemplateLib->addPlanMessage($filter); //同步模板库
//                }
//            } else {
            $this->title = $filter['title'];
            $this->doctor_id = $filter['doctor_id'];
            $this->clinic_id = isset($filter['clinic_id']) ? $filter['clinic_id'] : "";
            $this->work_id = $filter['work_id'];
            $this->hour = $filter['hour'];
            $res = $this->save();
            if ($res) {
                //自动同步模板库
                $temp_id = $FollowPlanTemplateLib->add($filter, $mes);
                $this->addLogs($filter); //添加发送人员
                $filter['auto_id'] = $this->id;
                $result = $this->addPlanMessage($filter, $mes);   //添加消息
            }
//            }
            if ($result) {
                DB::commit(); // 提交事务
                return ["auto_id" => $filter['auto_id'], "temp_id" => isset($temp_id['temp_id']) ? $temp_id['temp_id'] : $filter['temp_id']];
            }
            DB::rollback(); // 回滚事务
            return "添加失败!";
        } catch (Exception $e) {
            DB::rollback(); // 回滚事务
        }
    }

    /**
     * 添加计划通过模板
     */
    public function addByTemplate($filter)
    {
        try {
            DB::beginTransaction(); // 开始事务
            $mes = $this->handelCombinationData($filter);
            $temp_info = (new FollowPlanTemplateLib())->detail($filter['template_id']);
            $this->title = $filter['title'];
            $this->doctor_id = $filter['doctor_id'];
            $this->clinic_id = isset($temp_info['clinic_id']) ? $temp_info['clinic_id'] : "";
            $this->work_id = $filter['work_id'];
            $this->hour = $filter['hour'];
            $res = $this->save();
            if ($res) {
                $this->addLogs($filter); //添加发送人员
                $filter['auto_id'] = $this->id;
//                $result = $this->addPlanMessageByTemp($filter);   //添加消息
                $result = $this->addPlanMessage($filter,$mes);   //添加消息
                (new FollowPlanTemplateLib())->where([['id','=',$filter['template_id']]])->increment('nums');
            }
            if ($result) {
                DB::commit(); // 提交事务
                return ["auto_id" => $this->id];
            }
            DB::rollback(); // 回滚事务
            return "添加失败!";
        } catch (Exception $e) {
            DB::rollback(); // 回滚事务
        }
    }

    /***
     * @param $filter
     * @return array|string
     * 直接发送模板
     */
    public function sendByTemplate($filter)
    {
        try {
            DB::beginTransaction(); // 开始事务
//            $mes = $this->handelCombinationData($filter);
            $temp_info = (new FollowPlanTemplateLib())->detail($filter['template_id']);
            $mes = (new FollowPlanTemplateLibMessage())->getMessages($filter['template_id']);
            $this->title = $temp_info['title'];
            $this->clinic_id = isset($temp_info['clinic_id']) ? $temp_info['clinic_id'] : "";
            $this->work_id = $filter['work_id'];
            $this->doctor_id = $filter['doctor_id'];
            $this->hour = $temp_info['hour'];
            $res = $this->save();
            if ($res) {
                $this->addLogs($filter); //添加发送人员
                $filter['auto_id'] = $this->id;
//                $result = $this->addPlanMessageByTemp($filter);   //添加消息
                $result = $this->addPlanMessage($filter,$mes,1);   //添加消息
                (new FollowPlanTemplateLib())->where([['id','=',$filter['template_id']]])->increment('nums');
            }
            if ($result) {
                DB::commit(); // 提交事务
                return ["auto_id" => $this->id];
            }
            DB::rollback(); // 回滚事务
            return "添加失败!";
        } catch (Exception $e) {
            DB::rollback(); // 回滚事务
        }
    }
    
    
    
    
    
    
    
    /***
     * @param $data
     *添加发送人员
     */
    public function addLogs($param)
    {
        $param['book_ids'] = Tool::handelString($param['book_ids']);
        $book = (new AddressBook());
        $data = [];
        $i = 0;
        foreach ($param['book_ids'] as $k => $v) {
            $res = $book::where([['id','=',$v]])->first();
            if(empty($res)){
                continue;
            }
            $data[$k]['book_id']  = $v;
            $data[$k]['work_id']  = $param['work_id'];
            $data[$k]['doctor_id']  = $param['doctor_id'];
            $data[$k]['user_id']  =$res->user_id;
            $data[$k]['type']  =3;
            $data[$k]['group_assistant_id']  =  $this->id;
            $data[$k]['created_at']  =  date("Y-m-d H:i:s",time());
            $data[$k]['updated_at']  =  date("Y-m-d H:i:s",time());
            $i++;
        }
        $yes = DB::table('c_group_assistant_logs')->insert($data);
        if($yes){
            return true;
        }
        return false;
    }



    /**
     *  添加自动随访消息
     */
    public function addPlanMessage($param, $mes,$type=0)
    {

        foreach ($mes as $k => $v) {
            $plan = new PlanMessage();
            $plan->message = $v['message'];//$param['message'];
            $plan->days = $v['days'];
            $plan->date_unit =$type==1?$v['date_unit']:$v['date'];
            $plan->auto_follow_plan_id = $param['auto_id'];
            $plan->work_id = $param['work_id'];
            $plan->save();
        }
        return true;
    }

    /**
     *  通过模板添加自动随访消息
     */
    public function addPlanMessageByTemp($param)
    {
        if(empty($param['infos'])){
            return false;
        }
        $data = [];
        foreach($param['infos'] as $k=>$v){
            $data[$k]['message']  = $v['message'];
            $data[$k]['date']  = $v['date'];
            $data[$k]['work_id']  = $param['work_id'];
            $data[$k]['auto_follow_plan_id']  = $this->id;
        }
        $yes = DB::table('c_plan_messages')->insert($data);
        if($yes){
            return true;
        }
    }


    /**
     * @param $param
     * 获取自动随访列表
     */
    public function getList($param)
    {
        $where[] = ['work_id', '=', $param['work_id']];
//        $where[] = ['doctor_id', '=', $param['doctor_id']];
        if(isset($param['type'])){
            $where[] = ['type', '=', $param['type']];
        }
        $res = $this->where($where)->with(['clinic'])->orderByDesc("id")->simplePaginate()->toArray();
        $plan =   new PlanMessage();
        if (!empty($res['data'])) {
            foreach ($res['data'] as $k => &$v) {
                $v['diff_time'] = $plan->where([['auto_follow_plan_id', '=', $v['id']]])->orderBy("days","desc")->value("date_unit");
//                if ($num > 1) {
//                    $start = $plan->where([['auto_follow_plan_id', '=', $v['id']]])->orderBy("date", "asc")->first();
//                    $end = $plan->where([['auto_follow_plan_id', '=', $v['id']]])->orderBy("date", "desc")->first();
//                    $v['diff_time'] = ceil((strtotime($end->date) - strtotime($start->date)) / 86400);
//                } else {
//                    $v['diff_time'] = 1;
//                }
            }
            $res['numbers'] = $this->getNumbers($param);
        }
        return $res;
    }

    /***
     * @param $filter
     * @return mixed
     * 获取自动随访详情随访
     */
    public function getDetail($filter)
    {
        $res = $this->where([['id', '=', $filter['id']]])->with(['clinic', 'planmessage'])->first()->toArray();
        return $res;
    }


    public  function getNumbers($filter)
    {
        $wait = $this->where([['type', '=', 0], ['work_id', '=', $filter['work_id']]])->count("id");
        $run = $this->where([['type', '=', 1], ['work_id', '=', $filter['work_id']]])->count("id");
        $complate = $this->where([['type', '=', 2], ['work_id', '=', $filter['work_id']]])->count("id");
        $dd['wait'] = $wait;
        $dd['run'] = $run;
        $dd['complate'] = $complate;
        return $dd;
    }


    public function addByTemplateForAndroid($filter)
    {
        try {
            DB::beginTransaction(); // 开始事务
        if (isset($filter['id'])) {
            $data = $this->getDetail($filter);
            foreach($data['planmessage'] as  $k=>$v){
                if ($k == $filter['key']) {
                    $mes['date'] = isset($filter['date'])?$filter['date']:$v['date'];
                    $mes['message'] =isset($filter['message'])?$filter['message']:$v['message'];
                    (new PlanMessage())->where([['id','=',$v['id']]])->update($mes);
                }
            }
            DB::commit(); // 提交事务
            return ["id" =>$filter['id']];
        } else if (isset($filter['template_id'])) {
            $res = (new FollowPlanTemplateLib())->detail($filter['template_id']);
            if (empty($res['tempmessage'])) {
                return "该模板消息为空,不能引用!";
            }
            $this->title = $res['title'];
            $this->content = $res['content'];
            $this->clinic_id = isset($res['clinic_id']) ? $res['clinic_id'] : "";
            $this->work_id = $filter['work_id'];
            $resd = $this->save();
            if ($resd) {
                $this->addLogs($filter); //添加发送人员
                foreach ($res['tempmessage'] as $k => $v) {
                    if ($k == $filter['key']) {
                        $mes['date'] = isset($filter['date'])?$filter['date']:$v['date'];
                        $mes['message'] = isset($filter['message'])?$filter['message']:$v['message'];
                    } else {
                        $mes['date'] = $v['date'];
                        $mes['message'] = $v['message'];
                    }
                    $mes['auto_id'] = $this->id;
                    $mes['work_id'] = $filter['work_id'];
                    $this->addPlanMessage($mes);   //添加消息
                }
                DB::commit(); // 提交事务
                return ["id" => $this->id];
            }
        }
            DB::rollback(); // 回滚事务
            return "添加失败!";
        } catch (Exception $e) {
            DB::rollback(); // 回滚事务
        }
    }

    /**
     * @param $param
     * @return array
     * 处理字符串分成数组
     */
    public function handelCombinationData($param)
    {
        $mes = Tool::handelString($param['message']);
        $date = Tool::handelString($param['date']);
        $arrs = [];
        foreach ($date as $k => $v) {
            $unit = mb_substr($v, -1);
            $num = substr($v, 0, -3);
            if ($unit == '周') {
                $num = $num * 7;
            } elseif ($unit == '月') {
                $num = $num * 30;
            }
            $days = $num;
            if($v=='0天'){
                $v = "当天";
            }
            $arrs[$k]['date'] = $v;
            $arrs[$k]['days'] = $days;
            foreach ($mes as $kk => $vv) {
                if ($k == $kk) {
                    $arrs[$k]['message'] = $vv;
                }
            }
        }
        return $arrs;
    }
    
}
